#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

#include "agc.h"

#define SAMPLERATE 16000
#define FRAMESIZE 160

int main(int argc, char *argv[])
{
    FILE *fidr = fopen(argv[1], "rb");
	FILE *fidw = fopen(argv[2], "wb");
    fseek(fidr, 0, SEEK_END); int d2 = ftell(fidr);
    fseek(fidr, 0, SEEK_SET); int d1 = ftell(fidr);	
    int frames = (d2-d1)/2/FRAMESIZE; // 10ms，16bit
    printf("total frames = %d\n", frames);

    int16_t inbuf[FRAMESIZE] = {0};
    int16_t outbuf[FRAMESIZE] = {0};
    int16_t *x = inbuf;
    int16_t *y = outbuf;
    /*
    kAgcModeAdaptiveAnalog  模拟音量调节
    kAgcModeAdaptiveDigital 自适应增益
    kAgcModeFixedDigital 固定增益
    */
    WebRtcAgcConfig agcConfig;
    agcConfig.compressionGaindB = 30; // default 9 dB
    agcConfig.limiterEnable = 1; // default kAgcTrue (on)
    agcConfig.targetLevelDbfs = 6; // default 3 (-3 dBOv)
    int minLevel = 0;
    int maxLevel = 255;

    void *agcInst = WebRtcAgc_Create();
    WebRtcAgc_Init(agcInst, minLevel, maxLevel, kAgcModeAdaptiveDigital, SAMPLERATE);
    size_t num_bands = 1;
    int inMicLevel, outMicLevel = -1;    
    uint8_t saturationWarning = 1;  //是否有溢出发生，增益放大以后的最大值超过了65536
    int16_t echo = 0;      
    WebRtcAgc_set_config(agcInst, agcConfig);

    for (int n=0; n<frames; n++)
    {
        printf("frame = %d\n", n);
        fread(inbuf, sizeof(int16_t), FRAMESIZE, fidr);
        inMicLevel = 0;
        WebRtcAgc_Process(agcInst, (const int16_t *const *) &x, num_bands, FRAMESIZE,
                                        (int16_t *const *) &y, inMicLevel, &outMicLevel, echo,
                                        &saturationWarning);
        fwrite(outbuf, sizeof(int16_t), FRAMESIZE, fidw);
    }
    WebRtcAgc_Free(agcInst);
    fclose(fidr); fclose(fidw);
    return 0;
}